import {
  _decorator,
  Camera,
  Component,
  geometry,
  Material,
  MeshRenderer,
  Node,
  RenderableComponent,
  Touch,
  v3,
} from "cc";
import RecastDetourManager from "./RecastDetourManager";
const { ccclass, property } = _decorator;

@ccclass("NavigationManager")
export class NavigationManager extends Component {
  private recastDetourManager!: RecastDetourManager;

  @property(Node)
  HerosNode: Node = null!;
  @property(Node)
  clickNode: Node = null!;
  @property(Camera)
  camera: Camera = null!;
  @property(Material)
  debugMaterial: Material = null!;

  private agent: Node;

  async start() {
    // 初始化navigation
    console.log("初始化navigation");
    this.recastDetourManager = await RecastDetourManager.getInstanceByNode(
      this.node,
      this.debugMaterial,
      1,
      this.node
    );
    console.log("this.recastDetourManager", this.recastDetourManager);
    // 添加角色
    // let [node, pool] = HeroManager.instance.createHeroNode(0);
    // node.setParent(this.node);
    // let id = this.recastDetourManager.addAgents(v3(0, 0, 0));
    // let role = this.get(this.pool, this.roleNode);
    // let comp = role.getComponent(RenderableComponent)!;
    // comp.unscheduleAllCallbacks();
    // comp.schedule(() => {
    //   role.setWorldPosition(
    //     this.recastDetourManager.crowd!.getAgentPosition(id)
    //   );
    // });

    this.clickNode.on(Node.EventType.TOUCH_END, this.onTouch, this);
  }
  protected update(dt: number): void {
    this.recastDetourManager?.update && this.recastDetourManager.update(dt);
  }
  onTouch(touch: Touch) {
    let ray = this.camera.screenPointToRay(
      touch.getLocationX(),
      touch.getLocationY()
    );
    let comps = this.node.getComponentsInChildren(MeshRenderer);
    let distance = Number.MAX_VALUE;
    for (let i = 0; i < comps.length; ++i) {
      let dis = geometry.intersect.rayModel(ray, comps[i].model!, {
        mode: geometry.ERaycastMode.CLOSEST,
        doubleSided: false,
        distance: Number.MAX_SAFE_INTEGER,
      });
      if (dis && dis < distance) {
        distance = dis;
      }
    }
    if (distance == Number.MIN_VALUE) {
      return;
    }
    let out = v3();
    ray.computeHit(out, distance);
    if (!this.agent) {
      // 添加角色
      // let [node, pool] = HeroManager.instance.createHeroNode(0);
      // node.setParent(this.HerosNode);
      // node.active = true;
      // node.setWorldPosition(out);
      // let id = this.recastDetourManager.addAgents(out);
      // let comp = node.getComponent(RenderableComponent)!;
      // //   comp.
      // this.schedule(() => {
      //   node.setWorldPosition(
      //     this.recastDetourManager.crowd!.getAgentPosition(id)
      //   );
      // });
      // this.agent = node;
      return;
    }
    this.recastDetourManager.agentGoto(out);
  }
}
